<?php

namespace App\Http\Controllers\Admin;

use App\DTOS\Admin\CustomerDTO;
use App\Exceptions\ServiceException;
use App\Exports\ExcelExport;
use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\Game\BanList;
use App\Models\Game\LoginLogs;
use App\Models\Game\LoginNum;
use App\Models\Game\Sale;
use App\Services\CustomerService;
use App\Utils\MyLog;
use App\Utils\ResponseUtil;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;

class CustomerLoginController extends Controller
{
    private CustomerService $customerService;
    private Request $request;
    public function __construct(Request $request,CustomerService $customerService)
    {
        $this->customerService = $customerService;
        $this->request = $request;
    }


    public function  buildData(){


        $dto = new CustomerDTO($this->request->all());
        $customerIds = $dto->getCustomerIds();//角色列表
        $phones = $dto->getPhones();//角色列表
        $phone = $dto->getPhone();
        $page = $dto->getPage();
        $pageSize = $dto->getLimit();
        $customerId = $dto->getCustomerId();
        $packageNo = $dto->getPackageNo();
        $createDateBegin = $dto->getCreateDateBegin();
        $createDateEnd = $dto->getCreateDateEnd();
        $model = LoginLogs::query();
        MyLog::info('开始时间'.json_encode($createDateBegin));
        MyLog::info('结束时间'.json_encode($createDateEnd));
        if ($createDateBegin) {
            $model->where('logindate', '>=', $createDateBegin);
        }
        if ($createDateEnd) {
            $model->where('logindate', '<=', $createDateEnd);
        }
        if ($customerId){
            $model->where('customer_id',$customerId);
        }

        if ($phone) {
            $model->where('cid','like','%'.$phone.'%');
        }
        if ($packageNo) {
            $model->where('packageNo',$packageNo);
        }
        if ($customerIds){
            $customerIdlists = explode("\n",$customerIds);
            $model->whereIn('customer_id',$customerIdlists);
        }
        if ($phones){
            $phoneids = explode("\n",$phones);
            $model->whereIn('cid',$phoneids);
        }
        $paginate= $model->orderByDesc('logindate')->paginate($pageSize,'*','page',$page);

            return $paginate;
    }


    public function paginate() { //table 数据

        $dto = new CustomerDTO($this->request->all());
        $iPs = $dto->getIPs();
        $customerIds = $dto->getCustomerIds();//角色列表
        $phones = $dto->getPhones();//角色列表
        $phone = $dto->getPhone();
        $page = $dto->getPage();
        $pageSize = $dto->getLimit();
        $customerId = $dto->getCustomerId();
        $packageNo = $dto->getPackageNo();
        $createDateBegin = $dto->getCreateDateBegin();
        $createDateEnd = $dto->getCreateDateEnd();
        $model = LoginLogs::query();

        if ($createDateBegin) {
            $model->where('logindate', '>=', $createDateBegin);
        }
        if ($createDateEnd) {
            $model->where('logindate', '<=', $createDateEnd);
        }
        if ($customerId){
            $model->where('customer_id',$customerId);
        }

        if ($phone) {
            $model->where('cid','like','%'.$phone.'%');
        }
        if ($packageNo) {
            $model->where('packageNo',$packageNo);
        }
        if ($customerIds){
            $customerIdlists = explode("\n",$customerIds);
            $model->whereIn('customer_id',$customerIdlists);
        }

        if ($iPs){
            $iPslists = explode("\n",$iPs);
            $model->whereIn('ip',$iPslists);
        }
        if ($phones){
            $phoneids = explode("\n",$phones);
            $model->whereIn('cid',$phoneids);
        }
        $paginate= $model->orderByDesc('logindate')->paginate($pageSize,'*','page',$page);
        $data = $paginate->items();
        foreach($data as &$datum){
            $datum['uuid'] = (string)$datum['id'];
            $datum['customer_id'] = (string)$datum['customer_id'];
        }
        $res = [];
        $res['code'] = 0;
        $res['data'] = $data;
        $res['count'] = $paginate->total();
        return ResponseUtil::json($res);
    }

    public function filter()
    { //table 数据导出

        $dto = new CustomerDTO($this->request->all());
        $createDateBegin = $dto->getCreateDateBegin();
        $createDateEnd = $dto->getCreateDateEnd();
        $gameArea = $dto->getGameArea();

        $input_str = "1,2,3,4";
        $input_numbers = explode(',', $input_str);
        $results = array();
        $searchData['createDateBegin']=$createDateBegin;
        $searchData['createDateEnd']=$createDateEnd;
        $res = callRpc("/RoleLoginService/paginate",$searchData,['gameArea'=>$gameArea]);
        if (empty($res['data'])){
            throw new \Exception("没有数据");
        }
        //筛选出相同ip地址的数据
        $res1=$this->filterIp($res['data']);
        return ResponseUtil::json($res1);

    }

    public function filterIp($data)
    {
        $ipServices = [];
        $duplicateIPServices = [];

        foreach ($data as $item) {
            $deviceId = $item['deviceId'];
            // 提取 IP 和 Mac
            preg_match('/IP:([^|]+)|Mac:([^|]+)/', $deviceId, $matches);
            $ip = $matches[1];
            $mac = $matches[2];

            // 存储 IP
            if (!empty($ip)) {
                if (!isset($ipServices[$ip])) {
                    $ipServices[$ip] = [];
                }
                $ipServices[$ip][] = $item;
            }
        }

        // 找出存在相同 IP 的数据
        foreach ($ipServices as $ip => $services) {
            if (count($services) > 1) {
                $duplicateIPServices[$ip] = $services;
            }
        }

        return $duplicateIPServices;
    }

    public function export(){ //table 数据导出
        $dto = new CustomerDTO($this->request->all());
        $paginate = $this->buildData($dto);
        $excelRows = [
            ['ID','账号渠道','登录账号','登录密码','包号','登录时间','最后登录区服','ip']
        ];
        foreach($paginate->items() as $datum){
            $excelRows[] = [
                $datum['customer_id']."\t",$datum['channel'],$datum['cid'],$datum['password'],$datum['packageNo'],
                strval($datum['logindate']),      $datum['serverid'] === null ? 0 : $datum['serverid'],$datum['ip'],
            ];
        }
        return ResponseUtil::success(cacheDownload(arrayToScvContent($excelRows),'.账号登录日志.csv'));

    }



    public function bindPaginate() { //账户绑定数据table 数据

        $dto = new CustomerDTO($this->request->all());
        $iPs = $dto->getIPs();
        $customerIds = $dto->getCustomerIds();//角色列表
        $phones = $dto->getPhones();//角色列表
        $phone = $dto->getPhone();
        $page = $dto->getPage();
        $pageSize = $dto->getLimit();
        $customerId = $dto->getCustomerId();
        $packageNo = $dto->getPackageNo();
        $createDateBegin = $dto->getCreateDateBegin();
        $createDateEnd = $dto->getCreateDateEnd();
        $model = Customer::query();

        if ($createDateBegin) {
            $model->where('created_at', '>=', $createDateBegin);
        }
        if ($createDateEnd) {
            $model->where('created_at', '<=', $createDateEnd);
        }
        if ($customerId){
            $model->where('id',$customerId);
        }

        if ($phone) {
            $model->where('phone','like','%'.$phone.'%');
        }
        if ($packageNo) {
            $model->where('packageNo',$packageNo);
        }
        if ($customerIds){
            $customerIdlists = explode("\n",$customerIds);
            $model->whereIn('customer_id',$customerIdlists);
        }

        if ($iPs){
            $iPslists = explode("\n",$iPs);
            $model->whereIn('ip',$iPslists);
        }
        if ($phones){
            $phoneids = explode("\n",$phones);
            $model->whereIn('phone',$phoneids);
        }
        if($phone==null ||  $phones==null){
            $model->whereNotNull('phone');
        }

        $paginate= $model->orderByDesc('updated_at')->whereNotNull('channel_uuid')->paginate($pageSize,'*','page',$page);
        $data = $paginate->items();
        foreach($data as &$datum){
            $datum['id'] = (string)$datum['id'].'\t';
            $datum['password'] = Crypt::decryptString($datum['password']);
        }
        $res = [];
        $res['code'] = 0;
        $res['data'] = $data;
        $res['count'] = $paginate->total();
        return ResponseUtil::json($res);
    }


    public function  bindbuildData(){


        $dto = new CustomerDTO($this->request->all());
        $customerIds = $dto->getCustomerIds();//角色列表
        $phones = $dto->getPhones();//角色列表
        $phone = $dto->getPhone();
        $page = $dto->getPage();
        $pageSize = $dto->getLimit();
        $customerId = $dto->getCustomerId();
        $packageNo = $dto->getPackageNo();
        $createDateBegin = $dto->getCreateDateBegin();
        $createDateEnd = $dto->getCreateDateEnd();
        $model = Customer::query();
        if ($createDateBegin) {
            $model->where('created_at', '>=', $createDateBegin);
        }
        if ($createDateEnd) {
            $model->where('created_at', '<=', $createDateEnd);
        }
        if ($customerId){
            $model->where('customer_id',$customerId);
        }

        if ($phone) {
            $model->where('phone','like','%'.$phone.'%');
        }
        if ($packageNo) {
            $model->where('packageNo',$packageNo);
        }
        if ($customerIds){
            $customerIdlists = explode("\n",$customerIds);
            $model->whereIn('customer_id',$customerIdlists);
        }

        if ($phones){
            $phoneids = explode("\n",$phones);
            $model->whereIn('phone',$phoneids);
        }
        if($phone==null ||  $phones==null){
            $model->whereNotNull('phone');
        }
        $paginate= $model->orderByDesc('created_at')->whereNotNull('channel_uuid')->paginate($pageSize,'*','page',$page);

        return $paginate;
    }


    public function bindexport(){ //table 数据导出
        $dto = new CustomerDTO($this->request->all());
        $paginate = $this->bindbuildData($dto);
        $excelRows = [
            ['ID','账号渠道','登录账号','登录密码','包号','登录时间','最后登录区服','ip']
        ];
        foreach($paginate->items() as $datum){
            $excelRows[] = [
                $datum['id']."\t",$datum['channel'],$datum['cid'], Crypt::decryptString($datum['password'])
            ,$datum['packageNo'],
                strval($datum['logindate']),      $datum['serverid'] === null ? 0 : $datum['serverid'],$datum['ip'],
            ];
        }
        return ResponseUtil::success(cacheDownload(arrayToScvContent($excelRows),'.账号登录日志.csv'));

    }

}
